//
//  ChatTextTableViewCell.m
//  TIMChat
//
//  Created by AlexiChen on 16/3/10.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ChatTableViewCell.h"
#import "TopUpViewController.h"
#import <AFNetworking.h>
#import <ZipArchive.h>
#import "UIView+RelativeCoordinate.h"


//==============================================================
@implementation ChatTextTableViewCell

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _chatText = [[UILabel alloc] init];
    _chatText.textAlignment = NSTextAlignmentLeft;
    _chatText.numberOfLines = 0;
    _chatText.lineBreakMode = NSLineBreakByWordWrapping;
    _chatText.userInteractionEnabled = YES;
    _chatBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    return _chatText;
}

- (void)configContent
{
    [super configContent];
    //文字消息颜色
    _chatText.font = [_msg textFont];
    _chatText.textColor = [_msg textColor];
    
    _chatText.frame = CGRectMake(0, 0, 200, 200);
    TIMTextElem *elem = (TIMTextElem *)[_msg.msg getElem:0];
    _chatText.text = [elem text];
}

@end
//==============================================================
@implementation ChatImageTableViewCell

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    //    _chatView = [[UIView alloc] init];
    
    
    
    _chatImage = [[UIImageView alloc] init];
    [_chatImage setFrame:CGRectMake(0, kDefaultMargin/2, 150, 60)];
    _chatImage.backgroundColor = [UIColor whiteColor];
    _chatImage.userInteractionEnabled = YES;

    return _chatImage;
}

- (void)onTapImage:(UITapGestureRecognizer *)tap
{
    if (tap.state == UIGestureRecognizerStateEnded)
    {
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        
        UIView *keyWindow = [UIApplication sharedApplication].keyWindow;
        CGRect rect = [_chatImage relativePositionTo:keyWindow];
        ChatImageBrowserView *view = [[ChatImageBrowserView alloc] initWithPicModel:_msg thumbnail:_chatImage.image fromRect:rect];
        [keyWindow addSubview:view];
    }
    
}

- (void)configContent
{
    [super configContent];
    
    TIMImageElem *elem = (TIMImageElem *)[_msg.msg getElem:0];
    
    __weak UIImageView *wci = _chatImage;
    [elem asyncThumbImage:^(NSString *path, UIImage *image, BOOL succ, BOOL isAsync) {
        wci.image = image ? image : [UIImage imageNamed:@"default_image"];
    } inMsg:_msg];
    _contentBack.image = [UIImage imageNamed:@""];
    
}

- (NSArray *)showMenuItems
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:[super showMenuItems]];
    
    if (_msg.status != EIMAMsg_SendFail && ![_msg isMineMsg])
    {
        UIMenuItem *saveItem = [[UIMenuItem alloc] initWithTitle:@"保存" action:@selector(saveImage:)];
        [array addObject:saveItem];
    }
    return array;
}

- (void)saveImage:(UIMenuItem *)item
{
    UIImageWriteToSavedPhotosAlbum(_chatImage.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error)
    {
        [[HUDHelper sharedInstance] tipMessage:@"已保存到相册"];
    }
    else
    {
        [[HUDHelper sharedInstance] tipMessage:[NSString stringWithFormat:@"保存失败 %@",error]];
    }
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can = [super canPerformAction:action withSender:sender] || action == @selector(saveImage:);
    return can;
}

@end

//==============================================================
@implementation ChatSoundTableViewCell

- (void)dealloc
{
    
}

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _soundButton = [[ImageTitleButton alloc] init];
    _soundButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [_soundButton addTarget:self action:@selector(onPlaySound) forControlEvents:UIControlEventTouchUpInside];
    _soundButton.userInteractionEnabled = YES;
    return _soundButton;
}

- (void)configSendingTips
{
    [super configSendingTips];
    if (_msg.status == EIMAMsg_WillSending)
    {
        _elemContentRef.hidden = YES;
       // [_contentBack startGlowing];
    }
    else
    {
        _elemContentRef.hidden = NO;
       //33 [_contentBack stopGlowing];
    }
    
}

- (void)configContent
{
    [super configContent];
    
    [self stopPlaySound];
    
    // 停止上一次的播放
    [_soundButton.imageView stopAnimating];
    
    BOOL isMine = [_msg isMineMsg];
    _soundButton.style = isMine ? ETitleLeftImageRight : EImageLeftTitleRight;
    [_soundButton setImage:isMine ? [UIImage imageNamed:@"my_voice3"] : [UIImage imageNamed:@"other_voice3"] forState:UIControlStateNormal];
    [_soundButton setTitleColor:[_msg textColor] forState:UIControlStateNormal];
    
    TIMSoundElem *elem = (TIMSoundElem *)[_msg.msg getElem:0];
    [_soundButton setTitle:[NSString stringWithFormat:@"%d''", elem.second] forState:UIControlStateNormal];
    
}

- (void)startPlaySoundAnimating
{
    BOOL isMine = [_msg isMineMsg];
    if (isMine)
    {
        _soundButton.imageView.animationImages = @[[UIImage imageNamed:@"my_voice1"], [UIImage imageNamed:@"my_voice2"], [UIImage imageNamed:@"my_voice3"]];
    }
    else
    {
        _soundButton.imageView.animationImages = @[[UIImage imageNamed:@"other_voice1"], [UIImage imageNamed:@"other_voice2"], [UIImage imageNamed:@"other_voice3"]];
    }
    
    _soundButton.imageView.animationDuration = 0.5;
    _soundButton.imageView.animationRepeatCount = 0;
    [_soundButton.imageView startAnimating];
}

- (void)stopPlaySoundAnimating
{
    [_soundButton.imageView stopAnimating];
    _soundButton.imageView.animationImages = nil;
}

- (void)startPlaySound
{
    [self startPlaySoundAnimating];
    TIMSoundElem *elem = (TIMSoundElem *)[_msg.msg getElem:0];
    __weak ChatSoundTableViewCell *ws = self;
    if (elem.data)
    {
        [[ChatSoundPlayer sharedInstance] playWith:elem.data finish:^{
            [ws stopPlaySoundAnimating];
        }];
    }
    else
    {
        [elem getSound:^(NSData *data) {
            [[ChatSoundPlayer sharedInstance] playWith:data finish:^{
                [ws stopPlaySoundAnimating];
            }];
        } fail:^(int code, NSString* err) {
            [[HUDHelper sharedInstance] tipMessage:[NSString stringWithFormat:@"播放语音失败:%@", IMALocalizedError(code, err)]];
        }];
    }
}

- (void)stopPlaySound
{
    [self stopPlaySoundAnimating];
    [[ChatSoundPlayer sharedInstance] stopPlay];
}

- (void)onPlaySound
{
    if (!_soundButton.imageView.isAnimating)
    {
        [self startPlaySound];
    }
    else
    {
        // 正在播放，再次点击，则停止播放
        [self stopPlaySound];
    }
}

@end

//==============================================================
@implementation ChatFileTableViewCell

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _filePanel = [[UIView alloc] init];
    
    _fileIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"input_image"]];
    [_fileIcon setFrame:CGRectMake(kDefaultMargin/2, kDefaultMargin/2, 60, 60)];
    [_filePanel addSubview:_fileIcon];
    
    _fileName = [[UILabel alloc] initWithFrame:CGRectMake(_fileIcon.bounds.size.width+kDefaultMargin, kDefaultMargin/2, 120, _fileIcon.bounds.size.height * 2/3)];
    _fileName.numberOfLines = 0;
    _fileName.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _fileName.font = kAppSmallTextFont;
    [_filePanel addSubview:_fileName];
    
    _fileSize = [[UILabel alloc] initWithFrame:CGRectMake(_fileIcon.bounds.size.width+kDefaultMargin, _fileName.origin.y+_fileName.size.height, 100, _fileIcon.bounds.size.height * 1/3)];
    _fileSize.font = kAppSmallTextFont;
    [_filePanel addSubview:_fileSize];
    
    return _filePanel;
}

- (void)configContent
{
    [super configContent];
    
    TIMFileElem *elem = (TIMFileElem *)[_msg.msg getElem:0];
    NSString *fileSize = [self calculSize:elem.fileSize];
    NSString *fileName = [elem.filename lastPathComponent];
    _fileName.text = fileName;
    _fileSize.text = fileSize;
    
}

//计算文件大小
- (NSString *)calculSize:(NSInteger)size
{
    int loopCount = 0;
    int mod=0;
    while (size >=1024)
    {
        mod = size%1024;
        size /= 1024;
        loopCount++;
        if (loopCount > 4)
        {
            break;
        }
    }
    
    CGFloat rate=1;
    int loop = loopCount;
    while (loop--)
    {
        rate *= 1000.0;
    }
    CGFloat fSize = size + (CGFloat)mod/rate;
    NSString *sizeUnit;
    switch (loopCount)
    {
        case 0:
            sizeUnit = [[NSString alloc] initWithFormat:@"%.0fB",fSize];
            break;
        case 1:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.1fKB",fSize];
            break;
        case 2:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.2fMB",fSize];
            break;
        case 3:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.3fGB",fSize];
            break;
        case 4:
            sizeUnit = [[NSString alloc] initWithFormat:@"%0.4fTB",fSize];
            break;
        default:
            break;
    }
    return sizeUnit;
}

- (NSArray *)showMenuItems
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:[super showMenuItems]];
    
    if (_msg.status != EIMAMsg_SendFail && ![_msg isMineMsg])
    {
        UIMenuItem *downloadItem = [[UIMenuItem alloc] initWithTitle:@"下载" action:@selector(downloadItem:)];
        [array addObject:downloadItem];
    }
    return array;
}

- (void)downloadItem:(id)sender
{
    DebugLog(@"downloadItem");
    
    TIMFileElem *elem = (TIMFileElem *)[_msg.msg getElem:0];
    
    if (!(elem.uuid && elem.uuid.length > 0))
    {
        [[HUDHelper sharedInstance] syncStopLoadingMessage:@"文件uuid为空"];
        return;
    }
    
    NSArray *cachesPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,  NSUserDomainMask,YES);
    NSString *ourCachesPath =[cachesPaths objectAtIndex:0];
    
    NSString *fileName=[ourCachesPath stringByAppendingPathComponent:[elem.filename lastPathComponent]];
    
    [[HUDHelper sharedInstance] syncLoading:@"正在下载"];
    
    [elem getFileData:^(NSData *data){
        
        [[HUDHelper sharedInstance] syncStopLoading];
        
        [data writeToFile:fileName atomically:YES];
        
        DebugLog(@"save path = %@", cachesPaths);
        NSString *msg = [[NSString alloc] initWithFormat:@"下载成功，文件已保存到%@",cachesPaths];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    } fail:^(int code,NSString *err){
        
        [[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, err)];
    }];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can = [super canPerformAction:action withSender:sender] || action == @selector(downloadItem:);
    return can;
}
@end
//==============================================================

@implementation ChatVideoTableViewCell

- (UIView *)addElemContent
{
    _videoPanel = [[MicroVideoPlayView alloc] initWithFrame:CGRectMake(0, 0, 150, 100)];
    return _videoPanel;
}

- (void)configContent
{
    [super configContent];
    
    [_videoPanel setMessage:_msg];
}

@end
@implementation ChatCustomTableViewCell

- (UIView *)addElemContent
{
    //    _chatView = [[UIView alloc] init];
    //    _chatView.backgroundColor = [UIColor grayColor];
    
    
    
    //    _chatImage = [[UIImageView alloc] init];
    //    [_chatImage setFrame:CGRectMake(0, kDefaultMargin/2, 150, 60)];
    //    [_chatView addSubview:_chatImage];
    //    //    _chatImage.backgroundColor = [UIColor whiteColor];
    //    _chatImage.userInteractionEnabled = YES;
    //
    //    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapImage:)];
    //    tap.numberOfTapsRequired = 1;
    //    tap.numberOfTouchesRequired = 1;
    //    [_chatImage addGestureRecognizer:tap];
    //
    //    [_remindLab removeFromSuperview];
    
    _remindLab = [[UILabel alloc] initWithFrame:CGRectMake(0, kDefaultMargin/2, XQScreenW, 30)];
    _remindLab.numberOfLines = 0;
    _remindLab.text = @"获取数据错误";
    _remindLab.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _remindLab.font = kAppSmallTextFont;
    //    _remindLab.backgroundColor = [UIColor greenColor];
    _remindLab.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_remindLab];
    
    
    
    
    return _remindLab;
}
- (void)configContent
{
    [super configContent];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    NSString *dataStr = [[NSString alloc] initWithData:elem.data encoding:NSUTF8StringEncoding];
    NSLog(@"ggggggddddddggg === %@", dataStr);
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    _remindLab.text = @"对话中";
//    [_msg remove];
    
    
    
    //    TIMImageElem *elem = (TIMImageElem *)[_msg.msg getElem:0];
    //
    //    __weak UIImageView *wci = _chatImage;
    //    [elem asyncThumbImage:^(NSString *path, UIImage *image, BOOL succ, BOOL isAsync) {
    //        wci.image = image ? image : [UIImage imageNamed:@"default_image"];
    //    } inMsg:_msg];
    _contentBack.image = [UIImage imageNamed:@""];
}

- (NSArray *)showMenuItems
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:[super showMenuItems]];
    
    if (_msg.status != EIMAMsg_SendFail && ![_msg isMineMsg])
    {
        UIMenuItem *saveItem = [[UIMenuItem alloc] initWithTitle:@"保存" action:@selector(saveImage:)];
        [array addObject:saveItem];
    }
    return array;
}

- (void)saveImage:(UIMenuItem *)item
{
    UIImageWriteToSavedPhotosAlbum(_chatImage.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error)
    {
        [[HUDHelper sharedInstance] tipMessage:@"已保存到相册"];
    }
    else
    {
        [[HUDHelper sharedInstance] tipMessage:[NSString stringWithFormat:@"保存失败 %@",error]];
    }
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can = [super canPerformAction:action withSender:sender] || action == @selector(saveImage:);
    return can;
}

@end
@implementation ChatCustomFreeImageViewCell

- (UIView *)addElemContent
{
    _chatView = [[UIView alloc] init];
    _chatImage = [[UIImageView alloc] init];
    [_chatImage setFrame:CGRectMake(0, 0, 170, 150)];
    [_chatView addSubview:_chatImage];
    _chatImage.layer.cornerRadius = 5;
    _chatImage.clipsToBounds = YES;
    _chatImage.contentMode = UIViewContentModeScaleAspectFill;
    _chatImage.autoresizingMask = UIViewAutoresizingNone;
    [_chatImage setContentScaleFactor:[[UIScreen mainScreen] scale]];
    
    _chatImage.layer.masksToBounds = YES;
    
    _chatImage.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapFreeImage:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_chatImage addGestureRecognizer:tap];
    
    return _chatView;
}
- (void)configContent
{
    [super configContent];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    [_chatImage sd_setImageWithURL:[NSURL URLWithString:elemCmd.imageUrl]];
    
    _contentBack.image = [UIImage imageNamed:@""];
}
- (void)onTapFreeImage:(UITapGestureRecognizer *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"celltap" object:nil];

    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    self.cyImageAvatar = [[CYImageAvatarBrowser alloc] init];
    [self.cyImageAvatar showImage:_chatImage with:elemCmd.imageUrl];
    
}
@end
@implementation ChatCustomFreeVideoViewCell

- (UIView *)addElemContent
{
    _chatView = [[UIView alloc] init];
    _chatView.backgroundColor = [UIColor whiteColor];
    
    
    
    _chatImage = [[UIImageView alloc] init];
    _chatImage.contentMode = UIViewContentModeScaleAspectFill;
    _chatView.clipsToBounds = YES;
    [_chatImage setFrame:CGRectMake(0, kDefaultMargin/2, 150, 150)];
    [_chatView addSubview:_chatImage];
    _chatImage.backgroundColor = [UIColor blueColor];
    _chatImage.userInteractionEnabled = YES;
    UIImageView *playImage = [[UIImageView alloc] initWithFrame:CGRectMake(55, 55, 40, 40)];
    playImage.image = [UIImage imageNamed:@"playlogo"];
    [_chatImage addSubview:playImage];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapFreeVideo:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_chatImage addGestureRecognizer:tap];
    return _chatView;
}
- (void)configContent
{
    [super configContent];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    NSString *dataStr = [[NSString alloc] initWithData:elem.data encoding:NSUTF8StringEncoding];
    NSLog(@"gggggg === %@", dataStr);
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    [_chatImage sd_setImageWithURL:[NSURL URLWithString:elemCmd.imageUrl]];
    
    
    _contentBack.image = [UIImage imageNamed:@""];
}

#pragma mark - 点击视频消息
- (void)onTapFreeVideo:(UITapGestureRecognizer *)sender {
//    NSDate *now = [NSDate date];
//    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//    fmt.dateFormat = kBMHRequestTimeFormat;
//    //时间戳
//    NSString *sTime = [fmt stringFromDate:now];
//    NSString *objID = @"0";
//    NSString *publicKey = @"BMH2014YDYWB";
//    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,@"26880152", publicKey, sTime];
//    nat = [nat md5Encrypt];
//    NSDate * senddate=[NSDate date];
//    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
//    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
//    NSString *locationString = [dateformatter stringFromDate:senddate];
//
//    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
//    NSString *dataStr = [[NSString alloc] initWithData:elem.data encoding:NSUTF8StringEncoding];
//    NSLog(@"gggggg === %@", dataStr);
//    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
////    老代码
////    NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",@"26880152",@"Userid",@"vvvIMG_0246.MOV",@"VideoName",@"tempvideo", @"bucketName", nil];
//
//    NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",elemCmd.videoUrl,@"VideoName",@"tempvideo", @"bucketName", nil];
//
//
//    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//    NSString *downloadVideoDirectory = [path stringByAppendingPathComponent:@"downloadVideo"];
//    if ([[NSFileManager defaultManager] fileExistsAtPath:downloadVideoDirectory] == NO) {
//        [[NSFileManager defaultManager] createDirectoryAtPath:downloadVideoDirectory withIntermediateDirectories:YES attributes:nil error:nil];
//    }
//    NSString *videoZIPName = elemCmd.videoUrl;
//    NSString *videoName = [[videoZIPName stringByDeletingPathExtension] stringByAppendingPathExtension:@"mp4"];
//    NSString *videoPath = [downloadVideoDirectory stringByAppendingPathComponent:videoName];
//
//    [BMHHTTPSession GET:@"MobileInterface/Video/VideoCloud.ashx" paraments:dicRegister success:^(id  _Nullable JSON) {
//        NSLog(@"视频连接==-=-=-=-=-=-%@", JSON);
//
//    } failure:^(NSError * _Nullable error) {
//
//    }];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"celltap" object:nil];
    
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *downloadVideoDirectory = [path stringByAppendingPathComponent:@"downloadVideo"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:downloadVideoDirectory] == NO) {
        [[NSFileManager defaultManager] createDirectoryAtPath:downloadVideoDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *videoZIPName = elemCmd.videoUrl;
    NSString *videoName = [[videoZIPName stringByDeletingPathExtension] stringByAppendingPathExtension:@"mp4"];
    NSString *videoPath = [downloadVideoDirectory stringByAppendingPathComponent:videoName];
    
    if ([_msg isMineMsg]){
        if ([[NSFileManager defaultManager] fileExistsAtPath:[path stringByAppendingPathComponent:videoName]]) {
            customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:[path stringByAppendingPathComponent:videoName] isFileUrl:YES];
            customerView.Delegate = self;
            
            [customerView.player play];
            [customerView.controlView setPlayButtonSelected:YES];
            [[UIApplication sharedApplication].keyWindow addSubview:customerView];
            return;
        }
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
            customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
            customerView.Delegate = self;
            
            [customerView.player play];
            [customerView.controlView setPlayButtonSelected:YES];
            [[UIApplication sharedApplication].keyWindow addSubview:customerView];
            return;
        }
        
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        //        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",elemCmd.videoUrl,@"VideoName",@"redvideo", @"bucketName", nil];
        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",elemCmd.videoUrl,@"VideoName",@"tempvideo", @"bucketName", nil];
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
        [BMHHTTPSession GET:@"MobileInterface/Video/VideoCloud.ashx" paraments:dicRegister success:^(id  _Nullable JSON) {
            NSLog(@"视频连接==-=-=-=-=-=-%@", JSON);
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            [HUD hide:YES];
            
            NSString *videoUrl = JSON[@"result"][@"errmsg"];
            if ([videoUrl containsString:@"dynamic"]) {
                videoUrl = [videoUrl stringByReplacingOccurrencesOfString:@"dynamic" withString:@"tempvideo"];
            }
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:videoUrl]];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
            hud.mode = MBProgressHUDModeDeterminate;
            [[manager downloadTaskWithRequest:request
                                     progress:^(NSProgress * _Nonnull downloadProgress) {
                                         hud.progress = downloadProgress.fractionCompleted;
                                     }
                                  destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                                      NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
                                      NSString *downloadZipDirectory = [path stringByAppendingPathComponent:@"downloadZip"];
                                      if ([[NSFileManager defaultManager] fileExistsAtPath:downloadZipDirectory] == NO) {
                                          [[NSFileManager defaultManager] createDirectoryAtPath:downloadZipDirectory withIntermediateDirectories:YES attributes:nil error:nil];
                                      }
                                      NSString *filePath = [downloadZipDirectory stringByAppendingPathComponent:videoZIPName];
                                      return [NSURL fileURLWithPath:filePath];
                                  }
                            completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                                if (error == nil) {
                                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                        [SSZipArchive unzipFileAtPath:filePath.resourceSpecifier
                                                        toDestination:downloadVideoDirectory
                                                      progressHandler:NULL
                                                    completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
                                                        dispatch_async(dispatch_get_main_queue(), ^{
                                                            [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                                            if (error == nil) {
                                                                [[NSFileManager defaultManager] removeItemAtURL:filePath error:nil];
                                                                customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
                                                                customerView.Delegate = self;
                                                                
                                                                [customerView.player play];
                                                                [customerView.controlView setPlayButtonSelected:YES];
                                                                [window addSubview:customerView];
                                                            } else {
                                                                [MBProgressHUD showContent:@"视频解压失败"];
                                                            }
                                                        });
                                                    }];
                                    });
                                } else {
                                    [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                    [MBProgressHUD showContent:@"视频下载失败"];
                                }
                            }] resume];
            
        } failure:^(NSError * _Nullable error) {
            [HUD hide:YES];
        }];
        
    }else {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl] == nil || [[[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl]  isEqual: @""]) {
            if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
                customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
                customerView.Delegate = self;
                
                [customerView.player play];
                [customerView.controlView setPlayButtonSelected:YES];
                [[UIApplication sharedApplication].keyWindow addSubview:customerView];
                return;
            }
            NSDate *now = [NSDate date];
            NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
            fmt.dateFormat = kBMHRequestTimeFormat;
            //时间戳
            NSString *sTime = [fmt stringFromDate:now];
            NSString *objID = @"0";
            NSString *publicKey = @"BMH2014YDYWB";
            NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
            nat = [nat md5Encrypt];
            NSDate * senddate=[NSDate date];
            NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
            NSString *locationString = [dateformatter stringFromDate:senddate];
            
            NSDictionary *  dic= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",elemCmd.videoUrl,@"VideoName",@"redvideo", @"bucketName", nil];
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
            [BMHHTTPSession GET:@"MobileInterface/Video/VideoCloud.ashx" paraments:dic success:^(id  _Nullable JSON) {
                NSLog(@"视频连接==-=-=-=-=-=-%@", JSON);
                [HUD hide:YES];
                //                    [_effectView removeFromSuperview];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"onTapPayVideo" object:nil];
                
                NSString *videoUrl = JSON[@"result"][@"errmsg"];
                if ([videoUrl containsString:@"dynamic"]) {
                    videoUrl = [videoUrl stringByReplacingOccurrencesOfString:@"dynamic" withString:@"tempvideo"];
                }
                AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:videoUrl]];
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
                hud.mode = MBProgressHUDModeDeterminate;
                [[manager downloadTaskWithRequest:request
                                         progress:^(NSProgress * _Nonnull downloadProgress) {
                                             hud.progress = downloadProgress.fractionCompleted;
                                         }
                                      destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                                          NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
                                          NSString *downloadZipDirectory = [path stringByAppendingPathComponent:@"downloadZip"];
                                          if ([[NSFileManager defaultManager] fileExistsAtPath:downloadZipDirectory] == NO) {
                                              [[NSFileManager defaultManager] createDirectoryAtPath:downloadZipDirectory withIntermediateDirectories:YES attributes:nil error:nil];
                                          }
                                          NSString *filePath = [downloadZipDirectory stringByAppendingPathComponent:videoZIPName];
                                          return [NSURL fileURLWithPath:filePath];
                                      }
                                completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                                    if (error == nil) {
                                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                            [SSZipArchive unzipFileAtPath:filePath.resourceSpecifier
                                                            toDestination:downloadVideoDirectory
                                                          progressHandler:NULL
                                                        completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
                                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                                [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                                                if (error == nil) {
                                                                    [[NSFileManager defaultManager] removeItemAtURL:filePath error:nil];
                                                                    customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
                                                                    customerView.Delegate = self;
                                                                    
                                                                    [customerView.player play];
                                                                    [customerView.controlView setPlayButtonSelected:YES];
                                                                    [window addSubview:customerView];
                                                                } else {
                                                                    [MBProgressHUD showContent:@"解压视频失败，请稍后重试"];
                                                                }
                                                            });
                                                        }];
                                        });
                                    } else {
                                        [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                        [MBProgressHUD showContent:@"下载视频失败，请稍后重试"];
                                    }
                                }] resume];
                
            } failure:^(NSError * _Nullable error) {
                [HUD hide:YES];
                
            }];
        }
        
    }
    
}


- (void)clickBackBtnVideoPlay {
    [customerView.player pause];
    [customerView removeFromSuperview];
}

@end
@implementation ChatCustomGiftViewCell

- (UIView *)addElemContent
{
    _chatView = [[UIView alloc] init];
    _chatImage = [[UIImageView alloc] init];
    [_chatImage setFrame:CGRectMake(0, 0, 100, 100)];
    _chatImage.contentMode = UIViewContentModeScaleAspectFit;
    _chatImage.autoresizingMask = UIViewAutoresizingNone;
    [_chatImage setContentScaleFactor:[[UIScreen mainScreen] scale]];
    
    [_chatView addSubview:_chatImage];
    
    
    return _chatView;
}
- (void)configContent
{
    [super configContent];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    [_chatImage sd_setImageWithURL:[NSURL URLWithString:elemCmd.giftMsgImage]];
    
    _contentBack.image = [UIImage imageNamed:@""];
}
@end
@implementation ChatCustomPayImageViewCell

- (UIView *)addElemContent
{
    _chatView = [[UIView alloc] init];
    
    _chatImage = [[UIImageView alloc] init];
    [_chatImage setFrame:CGRectMake(0, 0, 170, 150)];
    _chatImage.layer.cornerRadius = 5;
    _chatImage.clipsToBounds = YES;
    _chatImage.contentMode = UIViewContentModeScaleAspectFill;
    _chatImage.autoresizingMask = UIViewAutoresizingNone;
    [_chatImage setContentScaleFactor:[[UIScreen mainScreen] scale]];
    
    _chatImage.layer.masksToBounds = YES;
    
    [_chatView addSubview:_chatImage];
    _chatImage.userInteractionEnabled = YES;
    
    _remindLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, 150, 30)];
    _remindLab.numberOfLines = 0;
    _remindLab.text = @"这里是收费图片";
    _remindLab.textColor = [UIColor lightGrayColor];
    _remindLab.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _remindLab.font = kAppSmallTextFont;
    _remindLab.textAlignment = NSTextAlignmentLeft;
    [_chatView addSubview:_remindLab];
    
    _labelText = [[UILabel alloc] initWithFrame:CGRectMake(150, 0, 16, 16)];
    _labelText.textColor = [UIColor whiteColor];
    _labelText.backgroundColor = [UIColor redColor];
    _labelText.layer.cornerRadius = 8;
    _labelText.layer.masksToBounds = YES;
    _labelText.userInteractionEnabled = YES;
    _labelText.textAlignment = NSTextAlignmentCenter;
    _labelText.font = [UIFont systemFontOfSize:13];
    
    [_chatImage addSubview:_labelText];
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapPayImage:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_chatView addGestureRecognizer:tap];
    
    
    
    
    return _chatView;
}
- (void)configContent
{
    [super configContent];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    [_chatImage sd_setImageWithURL:[NSURL URLWithString:elemCmd.imageUrl]];
    _contentBack.image = [UIImage imageNamed:@""];
    if ([_msg isMineMsg])
    {
        _remindLab.text = [NSString stringWithFormat:@"对方需%ld个金豆解锁图片", [elemCmd.price integerValue]];
        _labelText.hidden = YES;
        
        
    }else {
        _remindLab.text = [NSString stringWithFormat:@"赠送%ld个金豆,阅后即焚", [elemCmd.price integerValue]];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl] == nil || [[[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl]  isEqual: @""]) {
            UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
            _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
            _effectView.frame = CGRectMake(0, 0, _chatImage.frame.size.width, _chatImage.frame.size.height);
            [_chatImage addSubview:_effectView];
            
        }else {
            [_effectView removeFromSuperview];
        }
        if ([[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl] == nil || [[[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl]  isEqual: @""]) {
            _labelText.hidden = YES;
            
        }else {
            
            _labelText.hidden = NO;
            
        }
        
        
    }
    
    
}
- (void)onTapPayImage:(UITapGestureRecognizer *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"celltap" object:nil];
    

    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    if ([_msg isMineMsg])
    {
        self.cyImageAvatar = [[CYImageAvatarBrowser alloc] init];
        [self.cyImageAvatar showImage:_chatImage with:elemCmd.imageUrl];
        
        
    }else {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl] == nil || [[[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl]  isEqual: @""]) {
            NSDate *now = [NSDate date];
            NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
            fmt.dateFormat = kBMHRequestTimeFormat;
            //时间戳
            NSString *sTime = [fmt stringFromDate:now];
            NSString *objID = @"0";
            NSString *publicKey = @"BMH2014YDYWB";
            NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
            nat = [nat md5Encrypt];
            NSDate * senddate=[NSDate date];
            NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
            NSString *locationString = [dateformatter stringFromDate:senddate];
            
            NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:elemCmd.payId,@"id",@"3",@"type",locationString,@"Timestamp",nat,@"Appsign", [[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"Userid",nil];
            
            [BMHHTTPSession GET:@"MobileInterface/User/RedImgVideo.ashx" paraments:dicRegister success:^(id  _Nullable JSON) {
                NSLog(@"解锁后的信息==-=-=-=-=-=-%@", JSON);
                
                if ([JSON[@"result"][@"errcode"] isEqualToString:@"0"]) {
                    //
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"onTapPayImage" object:nil];
                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:elemCmd.imageUrl];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    self.cyImageAvatar = [[CYImageAvatarBrowser alloc] init];
                    self.cyImageAvatar.delegate = self;
                    
                    [self.cyImageAvatar showImage:_chatImage with:elemCmd.imageUrl];
                    [_effectView removeFromSuperview];
                    IMAMsg *msg = [IMAMsg msgWithText:@"[系统提示]对方解锁了你的图片"];
                    IMAUser *user;
                    user.userId = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
                    TIMConversation     *conversation;
                    
                    conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:self.useID];
                    [conversation sendMessage:msg.msg succ:^{
                        [msg remove];
                        
                    } fail:^(int code, NSString *msg) {
                        NSLog(@"shibai == %@ --- %d", msg, code);
                        
                    }];
                    
                    
                } else if ([JSON[@"result"][@"errcode"] isEqualToString:@"-2"]){
                    UIViewController *viewController = [HelpTool viewControllerOfView:self];
                    
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的余额不足,是否前往充值?" preferredStyle: UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        //点击按钮的响应事件；
                        
                        
                    }]];
                    [alert addAction:[UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                        topVC.In_purchase = isIn_purchase;
                        [viewController.navigationController pushViewController:topVC animated:YES];
//
                        
                    }]];
                    [viewController.navigationController presentViewController:alert animated:YES completion:nil];
                    
                    
                }else if ([JSON[@"result"][@"errcode"] isEqualToString:@"-3"]){
                    [HelpTool startTipViewWithText:@"已解锁" duration:1 type:kTipViewTypeNone];
                }
                else {
                    [HelpTool startTipViewWithText:@"解锁失败" duration:1 type:kTipViewTypeNone];
                }
            } failure:^(NSError * _Nullable error) {
                
            }];
            
            
        }else {
            [HelpTool startTipViewWithText:@"正在焚毁中" duration:1 type:kTipViewTypeNone];
            
        }
        
    }
    
    
    
    
    
}
-(void)timeFireMethod{
    //倒计时-1
    secondsCountDown--;
    //修改倒计时标签现实内容
    self.labelText.text=[NSString stringWithFormat:@"%d",secondsCountDown];
    //当倒计时到0时，做需要的操作，比如验证码过期不能提交
    if(secondsCountDown==0){
        [countDownTimer invalidate];
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_DeleteNotification object:_msg];
        
        
        
    }
}
- (void)cyimgeShowOver {
    if (![_msg isMineMsg]){
        [_msg remove];
        
        secondsCountDown = 5;
        //开始倒计时
        countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
        self.labelText.hidden = NO;
        //设置倒计时显示的时间
        self.labelText.text=[NSString stringWithFormat:@"%d",secondsCountDown];
        
        
    }
}


@end
@implementation ChatCustomPayVideoViewCell

- (UIView *)addElemContent
{
    _chatView = [[UIView alloc] init];
    _chatImage = [[UIImageView alloc] init];
    [_chatImage setFrame:CGRectMake(0, 0, 150, 150)];
    _chatImage.layer.cornerRadius = 5;
    _chatImage.layer.masksToBounds = YES;
    [_chatView addSubview:_chatImage];
    _chatImage.userInteractionEnabled = YES;
    
    UIImageView *playImage = [[UIImageView alloc] initWithFrame:CGRectMake(55, 55, 40, 40)];
    playImage.image = [UIImage imageNamed:@"playlogo"];
    [_chatImage addSubview:playImage];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapPayVideo:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_chatImage addGestureRecognizer:tap];
    
    
    _labelText = [[UILabel alloc] initWithFrame:CGRectMake(130, 0, 16, 16)];
    _labelText.textColor = [UIColor whiteColor];
    _labelText.backgroundColor = [UIColor redColor];
    _labelText.layer.cornerRadius = 8;
    _labelText.layer.masksToBounds = YES;
    _labelText.userInteractionEnabled = YES;
    _labelText.textAlignment = NSTextAlignmentCenter;
    _labelText.font = [UIFont systemFontOfSize:13];
    
    [_chatImage addSubview:_labelText];
    
    [_remindLab removeFromSuperview];
    _remindLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, 150, 35)];
    _remindLab.numberOfLines = 2;
    _remindLab.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _remindLab.font = kAppSmallTextFont;
    _remindLab.textColor = [UIColor lightGrayColor];
    _remindLab.textAlignment = NSTextAlignmentLeft;
    [_chatView addSubview:_remindLab];
    

    
    
    
    return _chatView;
}
- (void)configContent
{
    [super configContent];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    NSString *dataStr = [[NSString alloc] initWithData:elem.data encoding:NSUTF8StringEncoding];
    NSLog(@"收费视频 === %@", dataStr);
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    [_chatImage sd_setImageWithURL:[NSURL URLWithString:elemCmd.imageUrl]];
    
    _contentBack.image = [UIImage imageNamed:@""];
    if ([_msg isMineMsg])
    {
        _remindLab.text = [NSString stringWithFormat:@"对方需%ld个金豆解锁视频", [elemCmd.price integerValue]];
        _labelText.hidden = YES;
        
        
    }else {
        _remindLab.text = [NSString stringWithFormat:@"赠送%ld个金豆,阅后即焚", [elemCmd.price integerValue]];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl] == nil || [[[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl]  isEqual: @""]) {
            _labelText.hidden = YES;
            UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
            _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
            _effectView.frame = CGRectMake(0, 0, _chatImage.frame.size.width, _chatImage.frame.size.height);
            [_chatImage addSubview:_effectView];

        }else {
            [_effectView removeFromSuperview];
            _labelText.hidden = NO;
            
        }
        
    }
    
}

#pragma mark - 付费视频点击时间
- (void)onTapPayVideo:(UITapGestureRecognizer *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"celltap" object:nil];
    
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *downloadVideoDirectory = [path stringByAppendingPathComponent:@"downloadVideo"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:downloadVideoDirectory] == NO) {
        [[NSFileManager defaultManager] createDirectoryAtPath:downloadVideoDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *videoZIPName = elemCmd.videoUrl;
    NSString *videoName = [[videoZIPName stringByDeletingPathExtension] stringByAppendingPathExtension:@"mp4"];
    NSString *videoPath = [downloadVideoDirectory stringByAppendingPathComponent:videoName];
    
    if ([_msg isMineMsg]){
        if ([[NSFileManager defaultManager] fileExistsAtPath:[path stringByAppendingPathComponent:videoName]]) {
            customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:[path stringByAppendingPathComponent:videoName] isFileUrl:YES];
            customerView.Delegate = self;

            [customerView.player play];
            [customerView.controlView setPlayButtonSelected:YES];
            [[UIApplication sharedApplication].keyWindow addSubview:customerView];
            return;
        }
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
            customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
            customerView.Delegate = self;
            
            [customerView.player play];
            [customerView.controlView setPlayButtonSelected:YES];
            [[UIApplication sharedApplication].keyWindow addSubview:customerView];
            return;
        }
        
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
//        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",elemCmd.videoUrl,@"VideoName",@"redvideo", @"bucketName", nil];
        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",elemCmd.videoUrl,@"VideoName",@"tempvideo", @"bucketName", nil];
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
        [BMHHTTPSession GET:@"MobileInterface/Video/VideoCloud.ashx" paraments:dicRegister success:^(id  _Nullable JSON) {
            NSLog(@"视频连接==-=-=-=-=-=-%@", JSON);
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            [HUD hide:YES];
            
            NSString *videoUrl = JSON[@"result"][@"errmsg"];
            if ([videoUrl containsString:@"dynamic"]) {
                videoUrl = [videoUrl stringByReplacingOccurrencesOfString:@"dynamic" withString:@"tempvideo"];
            }
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:videoUrl]];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
            hud.mode = MBProgressHUDModeDeterminate;
            [[manager downloadTaskWithRequest:request
                                     progress:^(NSProgress * _Nonnull downloadProgress) {
                                         hud.progress = downloadProgress.fractionCompleted;
                                     }
                                  destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                                      NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
                                      NSString *downloadZipDirectory = [path stringByAppendingPathComponent:@"downloadZip"];
                                      if ([[NSFileManager defaultManager] fileExistsAtPath:downloadZipDirectory] == NO) {
                                          [[NSFileManager defaultManager] createDirectoryAtPath:downloadZipDirectory withIntermediateDirectories:YES attributes:nil error:nil];
                                      }
                                      NSString *filePath = [downloadZipDirectory stringByAppendingPathComponent:videoZIPName];
                                      return [NSURL fileURLWithPath:filePath];
                                  }
                            completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                                if (error == nil) {
                                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                        [SSZipArchive unzipFileAtPath:filePath.resourceSpecifier
                                                        toDestination:downloadVideoDirectory
                                                      progressHandler:NULL
                                                    completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
                                                        dispatch_async(dispatch_get_main_queue(), ^{
                                                            [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                                            if (error == nil) {
                                                                [[NSFileManager defaultManager] removeItemAtURL:filePath error:nil];
                                                                customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
                                                                customerView.Delegate = self;
                                                                
                                                                [customerView.player play];
                                                                [customerView.controlView setPlayButtonSelected:YES];
                                                                [window addSubview:customerView];
                                                            } else {
                                                                [MBProgressHUD showContent:@"视频解压失败"];
                                                            }
                                                        });
                                                    }];
                                    });
                                } else {
                                    [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                    [MBProgressHUD showContent:@"视频下载失败"];
                                }
                            }] resume];
            
        } failure:^(NSError * _Nullable error) {
            [HUD hide:YES];
        }];
        
    }else {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl] == nil || [[[NSUserDefaults standardUserDefaults] objectForKey:elemCmd.imageUrl]  isEqual: @""]) {
            if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
                customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
                customerView.Delegate = self;
                
                [customerView.player play];
                [customerView.controlView setPlayButtonSelected:YES];
                [[UIApplication sharedApplication].keyWindow addSubview:customerView];
                return;
            }
            if ([[[XLAccountManager shareInstance] model].AccountBalanceString floatValue] > [elemCmd.price floatValue]) {
                NSDate *now = [NSDate date];
                NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
                fmt.dateFormat = kBMHRequestTimeFormat;
                //时间戳
                NSString *sTime = [fmt stringFromDate:now];
                NSString *objID = @"0";
                NSString *publicKey = @"BMH2014YDYWB";
                NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
                nat = [nat md5Encrypt];
                NSDate * senddate=[NSDate date];
                NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
                [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
                NSString *locationString = [dateformatter stringFromDate:senddate];
                
                NSDictionary *  dic= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",elemCmd.videoUrl,@"VideoName",@"redvideo", @"bucketName", nil];
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
                [BMHHTTPSession GET:@"MobileInterface/Video/VideoCloud.ashx" paraments:dic success:^(id  _Nullable JSON) {
                    NSLog(@"视频连接==-=-=-=-=-=-%@", JSON);
                    [HUD hide:YES];
                    [_effectView removeFromSuperview];
                    UIWindow *window = [UIApplication sharedApplication].keyWindow;
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"onTapPayVideo" object:nil];
                    
                    NSString *videoUrl = JSON[@"result"][@"errmsg"];
                    if ([videoUrl containsString:@"dynamic"]) {
                        videoUrl = [videoUrl stringByReplacingOccurrencesOfString:@"dynamic" withString:@"tempvideo"];
                    }
                    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
                    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:videoUrl]];
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_chatImage animated:YES];
                    hud.mode = MBProgressHUDModeDeterminate;
                    [[manager downloadTaskWithRequest:request
                                             progress:^(NSProgress * _Nonnull downloadProgress) {
                                                 hud.progress = downloadProgress.fractionCompleted;
                                             }
                                          destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                                              NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
                                              NSString *downloadZipDirectory = [path stringByAppendingPathComponent:@"downloadZip"];
                                              if ([[NSFileManager defaultManager] fileExistsAtPath:downloadZipDirectory] == NO) {
                                                  [[NSFileManager defaultManager] createDirectoryAtPath:downloadZipDirectory withIntermediateDirectories:YES attributes:nil error:nil];
                                              }
                                              NSString *filePath = [downloadZipDirectory stringByAppendingPathComponent:videoZIPName];
                                              return [NSURL fileURLWithPath:filePath];
                                          }
                                    completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                                        if (error == nil) {
                                            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                                [SSZipArchive unzipFileAtPath:filePath.resourceSpecifier
                                                                toDestination:downloadVideoDirectory
                                                              progressHandler:NULL
                                                            completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
                                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                                    [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                                                    if (error == nil) {
                                                                        [[NSFileManager defaultManager] removeItemAtURL:filePath error:nil];
                                                                        customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:videoPath isFileUrl:YES];
                                                                        customerView.Delegate = self;
                                                                        
                                                                        [customerView.player play];
                                                                        [customerView.controlView setPlayButtonSelected:YES];
                                                                        [window addSubview:customerView];
                                                                    } else {
                                                                        [MBProgressHUD showContent:@"解压视频失败，请稍后重试"];
                                                                    }
                                                                });
                                                            }];
                                            });
                                        } else {
                                            [MBProgressHUD hideHUDForView:_chatImage animated:YES];
                                            [MBProgressHUD showContent:@"下载视频失败，请稍后重试"];
                                        }
                                    }] resume];
                    
                } failure:^(NSError * _Nullable error) {
                    [HUD hide:YES];

                }];

            }else {
                UIViewController *viewController = [HelpTool viewControllerOfView:self];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的余额不足,是否前往充值?" preferredStyle: UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //点击按钮的响应事件；
                    
                    
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                    topVC.In_purchase = isIn_purchase;
                    [viewController.navigationController pushViewController:topVC animated:YES];
                    
                    
                }]];
                [viewController.navigationController presentViewController:alert animated:YES completion:nil];
 
            }

            
            
        }else {
            [HelpTool startTipViewWithText:@"正在焚毁中" duration:1 type:kTipViewTypeNone];
            
        }
        
    }
    
    
}
- (void)videoIsStartToPlay {
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];

    if (![_msg isMineMsg]){
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:elemCmd.payId,@"id",@"3",@"type",locationString,@"Timestamp",nat,@"Appsign", [[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"Userid",nil];
        [BMHHTTPSession GET:@"MobileInterface/User/RedImgVideo.ashx" paraments:dicRegister success:^(id  _Nullable JSON) {
            NSLog(@"解锁后的信息==-=-=-=-=-=-%@", JSON);
            if ([JSON[@"result"][@"errcode"] isEqualToString:@"0"]) {
                
                IMAMsg *msg = [IMAMsg msgWithText:@"[系统提示]对方解锁了你的视频"];
                IMAUser *user;
                user.userId = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
                TIMConversation     *conversation;
                
                conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:self.useID];
                [conversation sendMessage:msg.msg succ:^{
                    [msg remove];
                    
                } fail:^(int code, NSString *msg) {
                    NSLog(@"shibai == %@ --- %d", msg, code);
                    
                }];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];

                
            } else if ([JSON[@"result"][@"errcode"] isEqualToString:@"-2"]){
                UIViewController *viewController = [HelpTool viewControllerOfView:self];
                
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的余额不足,是否前往充值?" preferredStyle: UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //点击按钮的响应事件；
                    
                    
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                    topVC.In_purchase = isIn_purchase;
                    [viewController.navigationController pushViewController:topVC animated:YES];
                    
                    
                }]];
                [viewController.navigationController presentViewController:alert animated:YES completion:nil];
                
                
                
                
            }else if ([JSON[@"result"][@"errcode"] isEqualToString:@"-3"]){
                [HelpTool startTipViewWithText:@"已解锁" duration:1 type:kTipViewTypeNone];
                
            }
            else {
                [HelpTool startTipViewWithText:@"解锁失败" duration:1 type:kTipViewTypeNone];
            }
        } failure:^(NSError * _Nullable error) {
            
        }];

    }else {
        
    }
}
-(void)timeFireMethod{
    //倒计时-1
    secondsCountDown--;
    //修改倒计时标签现实内容
    self.labelText.text=[NSString stringWithFormat:@"%d",secondsCountDown];
    //当倒计时到0时，做需要的操作，比如验证码过期不能提交
    if(secondsCountDown==0){
        [countDownTimer invalidate];
        self.labelText.hidden = YES;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_DeleteNotification object:_msg];
        
        
        
    }
}

- (void)clickBackBtnVideoPlay {
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    if (customerView.playItem.status == AVPlayerStatusReadyToPlay) {
        if (![_msg isMineMsg]){
            
            [_msg remove];
            secondsCountDown = 5;//60秒倒计时
            //        //开始倒计时
            countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
            self.labelText.hidden = NO;
            //设置倒计时显示的时间
            self.labelText.text=[NSString stringWithFormat:@"%d",secondsCountDown];
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:elemCmd.imageUrl];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }
        
        [customerView.player pause];
        [customerView removeFromSuperview];
        
    }else {
        NSLog(@"cuowuuuu");
        
        [customerView.player pause];
        [customerView removeFromSuperview];
        
    }
}
@end
@implementation ChatFaceToFaceViewCell

// 只创建，外部统一添加
- (UIView *)addElemContent
{
    _chatText = [[UILabel alloc] init];
    _chatText.textAlignment = NSTextAlignmentCenter;
    _chatText.numberOfLines = 0;
    _chatText.lineBreakMode = NSLineBreakByWordWrapping;
    _chatText.userInteractionEnabled = YES;
    
    //    _chatBtn.backgroundColor = [UIColor redColor];
    
    //    UIImage *normal = [UIImage imageNamed:@"liaotian-lan"];
    //    normal = [normal resizableImageWithCapInsets:UIEdgeInsetsMake(25, 20, 8, 30)];
    //    [_chatBtn setBackgroundImage:normal forState:UIControlStateNormal];
    //        [_chatBtn addSubview:_chatText];
    
    return _chatText;
}

- (void)configContent
{
    [super configContent];
    
    _chatText.font = [_msg textFont];
    _chatText.textColor = [_msg textColor];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    
    CustomElemCmd *elemCmd = [[CustomElemCmd alloc] parseFaceCustom:(TIMCustomElem *)elem];
    NSLog(@"%ld",(long)elemCmd.action);
    if ([_msg isMineMsg]) {
        if (elemCmd.command == 1 ) {
            _chatText.text = @"对方无应答";
        }else if (elemCmd.command == 2) {
            _chatText.text = @"已拒绝";
        }else if (elemCmd.command == 3) {
            _chatText.text = @"已挂断";
        }
    }else {
        if (elemCmd.command == 1 ) {
            _chatText.text = @"对方已取消";
        }else if (elemCmd.command == 2) {
            _chatText.text = @"对方已拒绝";
        }else if (elemCmd.command == 3) {
            _chatText.text = @"对方已挂断";
        }
    }
}

@end
@interface ChatCustomShareViewCell ()
@property (nonatomic, strong) NSString *videoId;
@end
@implementation ChatCustomShareViewCell

- (UIView *)addElemContent
{
    _chatView = [[UIView alloc] init];
    _chatImage = [[UIImageView alloc] init];
    _playImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bmh_recommend_play_icon"]];
    [_chatImage setFrame:CGRectMake(0, 0, 150, 185)];
    //_playImage.frame = CGRectMake(_chatImage.width / 2 - 25, _chatImage.height / 2 - 25, 50, 50);
    _chatImage.userInteractionEnabled = YES;
    _chatImage.layer.masksToBounds = YES;
    _chatImage.layer.cornerRadius = 3;
    _chatImage.contentMode = UIViewContentModeScaleAspectFit;
    _chatImage.autoresizingMask = UIViewAutoresizingNone;
    [_chatImage setContentScaleFactor:[[UIScreen mainScreen] scale]];
    
    [_chatView addSubview:_chatImage];
    [_chatImage addSubview:_playImage];

    [_playImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_chatImage.mas_centerX);
        make.centerY.equalTo(_chatImage.mas_centerY);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoCoverTap:)];
    [_chatImage addGestureRecognizer:tap];

    return _chatView;
}
- (void)configContent
{
    [super configContent];
    
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    _videoId = elemCmd.videoId;
    [_chatImage sd_setImageWithURL:[NSURL URLWithString:elemCmd.videoCover]];
    
    _contentBack.image = [UIImage imageNamed:@""];
}

- (void)videoCoverTap:(UITapGestureRecognizer *)tap {

    UIViewController *viewController = [HelpTool viewControllerOfView:self];
    
    
//    BMHPlayPageVController *playPageVC = [[BMHPlayPageVController alloc]init];
//    playPageVC.dataSource = [NSMutableArray array];
//    //playPageVC.picDataArray = [NSMutableArray array];
//    
//    [playPageVC.dataSource addObject:self.videoId];
//    //[playPageVC.picDataArray addObject:model.gcUrl];
//    
//    playPageVC.indexPath = [playPageVC.dataSource indexOfObject:self.videoId];
//    [viewController.navigationController pushViewController:playPageVC animated:YES];
    
}

@end
@implementation ChatGirlInvitFaceViewCell
- (UIView *)addElemContent
{
    _chatView = [[UIView alloc] init];
    
    _chatImage = [[UIImageView alloc] init];
    [_chatImage setFrame:CGRectMake(0, 0, 150, 150)];
    _chatImage.layer.cornerRadius = 5;
    _chatImage.clipsToBounds = YES;
    _chatImage.contentMode = UIViewContentModeScaleAspectFill;
    _chatImage.autoresizingMask = UIViewAutoresizingNone;
    [_chatImage setContentScaleFactor:[[UIScreen mainScreen] scale]];
    
    _chatImage.layer.masksToBounds = YES;
    
    [_chatView addSubview:_chatImage];
    _chatImage.userInteractionEnabled = YES;
    
    _remindLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 158, 150, 15)];
    _remindLab.numberOfLines = 0;
    _remindLab.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _remindLab.font = kAppSmallTextFont;
    _remindLab.textColor = [UIColor lightGrayColor];
    _remindLab.textAlignment = NSTextAlignmentLeft;
    [_chatView addSubview:_remindLab];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapGirlInvitImage)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_chatView addGestureRecognizer:tap];
    return _chatView;
}
- (void)configContent
{
    [super configContent];
    NSMutableAttributedString *attri =     [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",@" 邀你视频聊天"]];
    
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [UIImage imageNamed:@"conten_icon_shipiaol_default"];
    // 设置图片大小
    attch.bounds = CGRectMake(0, 0, 16, 12);
    
    // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attri insertAttributedString:string atIndex:0];
    _remindLab.attributedText = attri;
    TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    
    [_chatImage sd_setImageWithURL:[NSURL URLWithString:elemCmd.imageUrl] placeholderImage:[UIImage imageNamed:@"BeautyPlaceholder"]];
    
    _contentBack.image = [UIImage imageNamed:@""];
}

- (void)onTapGirlInvitImage {
    if (![_msg isMineMsg]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatGirlInvitFaceViewCell" object:nil];

    }

}

@end


